package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.core.service.*;
import com.wondertek.poms.dao.po.EquityTreeAbilityLog;
import com.wondertek.poms.dao.po.EquityTreeMQLog;
import com.wondertek.poms.dao.po.ProductGropMember;
import com.wondertek.poms.dao.po.ProductGroup;
import com.wondertek.poms.dao.pojo.ProductGroupPojo;
import com.wondertek.poms.dao.repo.IProductGroupDao;
import javassist.expr.NewArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.Transient;
import java.util.*;


@Service
public class ProductGroupServiceImpl extends ServiceImpl<ProductGroup,Long> implements IProductGroupService {

	@PersistenceContext
    public EntityManager entityManager;
    @Autowired
    private IProductGropMemberService productGropMemberService;
    @Autowired
    private IProductGroupDao productGroupDao;
    @Autowired
    private ISystemConfigService systemConfigService;



    @Override
    public Page<ProductGroupPojo> findAll(ProductGroupPojo productGroupPojo, int page, int rows, String sord, String sidx) {
        StringBuilder condition = sqlStringWhere(productGroupPojo,sord,sidx);
        Object o = entityManager
                .createNativeQuery("select count(*) from ( " + condition.toString() + " ) a").getSingleResult();
        int count = Convert.toInt(o);
        Pageable pageable = getPageable(page - 1, rows, sord, sidx);

        if(count>0){
            Query query=entityManager.createNativeQuery(condition.toString());
            query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            query.setMaxResults(pageable.getPageSize());
            List<Object[]> resultListlist=query.getResultList();
            List<ProductGroupPojo> list=getList(resultListlist);
            PageImpl<ProductGroupPojo> result=new PageImpl<>(list,pageable,count);
            entityManager.close();
            return result;
        }
        entityManager.close();
        return Page.empty(pageable);
    }

    @Override
    @Transactional
    public ProductGroup saveProductGroup(ProductGroupPojo productGroupPojo) {
        ProductGroup productGroup=new ProductGroup();
        BeanUtils.copyProperties(productGroupPojo,productGroup);
        ProductGroup.putTimeAndUser(productGroup);
        productGroup.setStatus("2");
        productGroup=jpaRepository.save(productGroup);

        if(!"".equals(productGroupPojo.getProductIds())){
            String[] productIds = productGroupPojo.getProductIds().split(",|，");
            for (String productId : productIds) {
                ProductGropMember productGropMember = new ProductGropMember();
                productGropMember.setGroupId(productGroup.getGroupId());
                productGropMember.setProductId(productId);
                productGropMember.setStatus("0");
                productGropMember.setCreateTime(new Date());
                productGropMemberService.save(productGropMember);
            }
        }
        return productGroup;
    }

    @Override
    public ProductGroupPojo getById(Long id) {
        ProductGroup productGroup=jpaRepository.getOne(id);
        List<ProductGropMember> productGropMembers=productGropMemberService.findAllByGroupId(id);
        String productIds="";
        if(productGropMembers.size()>0) {
            for(ProductGropMember productGropMember:productGropMembers){
                productIds+=","+productGropMember.getProductId();
            }
            productIds=productIds.substring(1);
        }
        ProductGroupPojo productGroupPojo=new ProductGroupPojo();
        BeanUtils.copyProperties(productGroup,productGroupPojo);
        productGroupPojo.setCreateTime(DateUtil.format(Convert.toLocalDateTime(productGroup.getCreateTime()),"yyyy-MM-dd HH:mm:ss"));
        productGroupPojo.setProductIds(productIds);
        return productGroupPojo;
    }

    @Override
    public List<Long> getAllProductGroupId(String vo) {
        List<Long> list= new ArrayList<>();
        if(StrUtil.isNotBlank(vo)){
            vo="%"+vo+"%";
            list=productGroupDao.getAllGroupIdLike(vo);
        }else{
            list=productGroupDao.getAllGroupId();
        }
        return list;
    }

    @Override
    public List<String> getAllProductGroupName(String vo) {
        List<String> list=new ArrayList<>();
        if(StrUtil.isNotBlank(vo)){
            vo="%"+vo+"%";
            list=productGroupDao.getAllGroupNameLike(vo);
        }else{
            list=productGroupDao.getAllGroupName();
        }
        return list;
    }

    @Override
    @Transactional
    public void deleteGroup(String id) {
        jpaRepository.deleteById(Convert.toLong(id));
        productGropMemberService.deleteByGroupId(Convert.toLong(id));
    }

    @Override
    public Map<String, Object> getProductGroupMap(Long groupId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Optional<ProductGroup> opt = productGroupDao.findById(groupId);
        ProductGroup productGroup=new ProductGroup();
        if(opt.isPresent()){
            productGroup=opt.get();
        }
        map.put("groupName", productGroup.getGroupName());
        map.put("groupId", groupId);
        map.put("chargeAlias", productGroup.getAlias());
        List<String> productIds = productGropMemberService.getProductIdsByGroupId(groupId);
        String chargeId = "";
        for(String productId:productIds){
            chargeId += productId + ",";
        }
        if(StringUtil.isNullStr(chargeId)){
            map.put("chargeId", chargeId);
        }else{
            map.put("chargeId", chargeId.substring(0,chargeId.length()-1));
        }

        return map;
    }

    @Override
    public ProductGroup findByGroupId(Long groupId) {
        return productGroupDao.findByGroupId(groupId);
    }


    public StringBuilder sqlStringWhere(ProductGroupPojo productGroupPojo,String sord, String sidx){
        StringBuilder condition=new StringBuilder();
        String sql="select GROUP_ID,GROUP_NAME,ALIAS,STATUS,CREATE_TIME,UPDATE_TIME from PRODUCT_GROUP where 1=1 ";
        condition.append(sql);

        if(productGroupPojo.getGroupId()!=null){
            condition.append("and GROUP_ID="+productGroupPojo.getGroupId()+" ");
        }
        if(StrUtil.isNotBlank(productGroupPojo.getGroupName())){
            condition.append("and GROUP_NAME='"+productGroupPojo.getGroupName()+"' ");
        }
        if(StrUtil.isNotBlank(productGroupPojo.getStatus())){
            condition.append("and STATUS="+productGroupPojo.getStatus()+" ");
        }
        if(StrUtil.isNotBlank(productGroupPojo.getStartTime())){
            condition.append("and CREATE_TIME > to_date('"+productGroupPojo.getStartTime()+"','yyyy-mm-dd hh24:mi:ss') ");
        }
        if(StrUtil.isNotBlank(productGroupPojo.getEndTime())){
            condition.append("and CREATE_TIME < to_date('"+productGroupPojo.getEndTime()+"','yyyy-mm-dd hh24:mi:ss') ");
        }
        condition.append("order by "+sidx+" "+sord);
        return condition;
    }

    public List<ProductGroupPojo> getList(List<Object[]> resultListlist){
        List<ProductGroupPojo> list=new ArrayList<>();
        for(Object[] temp:resultListlist){
            ProductGroupPojo pojo=new ProductGroupPojo();
            pojo.setGroupId(Convert.toLong(temp[0]));
            pojo.setGroupName(Convert.toStr(temp[1]));
            pojo.setAlias(Convert.toStr(temp[2]));
            pojo.setStatus(Convert.toStr(temp[3]));
            pojo.setCreateTime(DateUtil.format(Convert.toLocalDateTime(temp[4]),"yyyy-MM-dd HH:mm:ss"));
            pojo.setUpdateTime(DateUtil.format(Convert.toLocalDateTime(temp[5]),"yyyy-MM-dd HH:mm:ss"));
            list.add(pojo);
        }
        return list;
    }

    @Override
    public ProductGroup deleteLogic(Long id) {
        return null;
    }

    @Override
    public ProductGroup merge(ProductGroup model) {
        return null;
    }
}
